package scheduler

import "spider/concurrent2/parser"

type QueueScheduler struct {
    // request channel
    requestChan chan parser.Request
    
    // worker channel,channel的数据是每个worker独享的request channel
    workerChan chan chan parser.Request
}

func (QueueScheduler *QueueScheduler) WorkerRequestChan() chan parser.Request {
    return  make(chan parser.Request)
}

// worker当前工作完成，准备接收新的工作
// 将worker的channel放入workerChan中,等待调度器重新分发任务
func (QueueScheduler *QueueScheduler) WorkerReady(RequestChan chan parser.Request) {
    QueueScheduler.workerChan <- RequestChan
}

// 提交request给调度器
func (QueueScheduler *QueueScheduler) Submit(request parser.Request) {
    // 添加到request channel
    QueueScheduler.requestChan <- request
}

// 调度器Run
func (QueueScheduler *QueueScheduler) Run() {
    QueueScheduler.workerChan  = make(chan chan parser.Request)
    QueueScheduler.requestChan = make(chan parser.Request)
    
    go func() {
        // request队列和worker队列
        var workerQueue  []chan parser.Request
        var requestQueue []parser.Request
        
        for {
            // 活动的request和worker
            var activeWorker chan parser.Request
            var activeRequest parser.Request
            
            // 获取空闲的worker和待处理的request
            if len(requestQueue) > 0 && len(workerQueue) > 0 {
                activeWorker  = workerQueue[0]
                activeRequest = requestQueue[0]
            }
            
            select {
            // 有新的request投递进来，放入request队列进行排队
            case request := <-QueueScheduler.requestChan:
                requestQueue = append(requestQueue,request)
                
            // worker任务执行完毕，准备接收新的任务，放入worker队列进行排队
            case worker := <-QueueScheduler.workerChan:
                workerQueue = append(workerQueue,worker)
                
            //  分发request给worker处理
            case activeWorker <- activeRequest:
                workerQueue  = workerQueue[1:]
                requestQueue = requestQueue[1:]
            }
        }
    }()
}
